package com.py.credit.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONObject;

public class ThreadMapCallable implements Callable<List<Map>> {
	
	
	private List<Map> listE;
	
	private String url;
	
	private String mapKey;
	
	public ThreadMapCallable(List<Map> listE,String url,String mapKey){
		this.listE=listE;
		this.url=url;
		this.mapKey=mapKey;
	}

	@Override
	public List<Map> call() throws Exception {
		if(StringUtils.isBlank(url)){
			url = "https://api.tianditu.gov.cn/geocoder";
		}
		if (listE != null && listE.size() > 0) {
			for (int i = 0; i < listE.size(); i++) {
				Map m = listE.get(i);
			    try{
				  
					String address = m.get("dz").toString();
					address=address.replaceAll("#", "").replaceAll("=", "").replaceAll("[+]", "").replaceAll("&", "").replaceAll("[?]", "").replaceAll("[/]", "");
					List<NameValuePair> list = new ArrayList<NameValuePair>();
				/*	list.add(new BasicNameValuePair("ds", "{\"keyWord\":\"" + address + "\"}"));
					list.add(new BasicNameValuePair("tk", mapKey));*/
					String uriI=url;
					String qt=URLEncoder.encode("\"","utf-8");
					String le=URLEncoder.encode("{","utf-8");
					String ri=URLEncoder.encode("}","utf-8");
					String par="?ds={\"keyWord\":\"" + address + "\"}";
					par=par.replaceAll("\"", qt).replaceAll("\\{", le).replaceAll("\\}", ri);
					uriI+=par;
					uriI+="&&tk="+mapKey;
					String content = LonAndLatUtil.getConn(uriI);
					if (content != null && !"".equals(content)) {
						JSONObject jsStr = JSONObject.parseObject(content);
						String status=jsStr.getString("status");
						if(!"0".equals(status)){
							continue;
						}
						String detail = jsStr.getString("location") == null ? "" : jsStr.get("location").toString();
						if(StringUtils.isBlank(detail)){
							listE.get(i).put("lon", "");
							listE.get(i).put("lat", "");
							continue;
						}
						JSONObject detailJson = JSONObject.parseObject(detail);
						if (detailJson != null && !detailJson.equals("")) {
						
							listE.get(i).put("lon", detailJson.get("lon").toString());
							listE.get(i).put("lat", detailJson.get("lat").toString());
						}
					}

			  }catch(Exception e){
				  System.out.println(e.getMessage()+m.toString());
			  }
				
			}
		}
		return listE;
	}

	public String getMapKey() {
		return mapKey;
	}

	public void setMapKey(String mapKey) {
		this.mapKey = mapKey;
	}

}
